package my.mvc;

import java.lang.reflect.Field;
import java.util.Comparator;

class ComparatorList implements Comparator {
    private String proName;
    private String proType = "string";

    public ComparatorList(String proName){
        this.proName = proName;
    }

    public ComparatorList(String proName, String proType){
        this.proName = proName;
        this.proType = proType;
    }

    public int compare(Object obj0, Object obj1) {
        Object value0 = getFieldValueByName(obj0);
        Object value1 = getFieldValueByName(obj1);

        if(value0 != null && value1 != null){
        	if(this.proType.equals("Long")){
                return (int)((Long)value0-(Long)value1);
            }
            if(this.proType.equals("string")){
                return (value0.toString().toLowerCase()).compareTo(value1.toString().toLowerCase());
            }
            //此处可根据不同条件进行扩展，比如整数int，或者ip规则等。
        }
        return 0;
    }

    public Object getFieldValueByName(Object obj){
        try {
            Field field = obj.getClass().getDeclaredField(this.proName);
            field.setAccessible(true);
            return field.get(obj);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }
}

